//
//  TRSeachActionViewController.m
//  WeiMiLan
//
//  Created by Mac on 14-8-25.
//  Copyright (c) 2014年 Mac. All rights reserved.
//
#define k_FontSize         (arc4random() % 15) + 14
#import "TRSeachActionViewController.h"
#import "KYRecentSearchView.h"

@interface TRSeachActionViewController ()
@property (strong, nonatomic) IBOutlet UITextField *seachWordTF;
@property (strong, nonatomic) IBOutlet UITextField *seachInTF;

@property (strong, nonatomic) IBOutlet TableViewWithBlock *tb;
@property (strong, nonatomic) IBOutlet UITextField *inputTextField;
@property (strong, nonatomic) IBOutlet UIButton *openButton;
@property (nonatomic) NSInteger selectIndex;

@property (strong, nonatomic)NSMutableArray *titlesArray;

@end

@implementation TRSeachActionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _tb.hidden=YES;
    self.directorys=@[@{@"ID":@"",@"NAME":@"全部"},@{@"ID":@"2219",@"NAME":@"服装"},@{@"ID":@"2218",@"NAME":@"包包"},@{@"ID":@"2217",@"NAME":@"丝巾"},@{@"ID":@"2216",@"NAME":@"手表"},@{@"ID":@"2215",@"NAME":@"鞋子"},@{@"ID":@"2214",@"NAME":@"眼镜"},@{@"ID":@"2213",@"NAME":@"皮带"},@{@"ID":@"2212",@"NAME":@"钱夹"},@{@"ID":@"2211",@"NAME":@"饰品"}];
    [self initNavigation];
    [self initSeachButton];
    
    
    [self updateKeyWordsUI:@[@"时尚",@"精品",@"美丽"]];
    
    [self seachRequest];
}

-(void)initSeachButton
{
    isOpened=NO;
    [_tb initTableViewDataSourceAndDelegate:^(UITableView *tableView,NSInteger section){
        
        return (NSInteger)self.directorys.count;
        
    } setCellForIndexPathBlock:^(UITableView *tableView,NSIndexPath *indexPath){
        SelectionCell *cell=[tableView dequeueReusableCellWithIdentifier:@"SelectionCell"];
        if (!cell) {
            cell=[[[NSBundle mainBundle]loadNibNamed:@"SelectionCell" owner:self options:nil]objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
       // [cell.lb setText:[NSString stringWithFormat:@"Select %d",indexPath.row]];
        cell.lb.text=self.directorys[indexPath.row][@"NAME"];
        return cell;
    } setDidSelectRowBlock:^(UITableView *tableView,NSIndexPath *indexPath){
        SelectionCell *cell=(SelectionCell*)[tableView cellForRowAtIndexPath:indexPath];
        _inputTextField.text=cell.lb.text;
        self.selectIndex=indexPath.row;
        [_openButton sendActionsForControlEvents:UIControlEventTouchUpInside];
    }];
    
    [_tb.layer setBorderColor:[UIColor lightGrayColor].CGColor];
    [_tb.layer setBorderWidth:2];
    
}
-(void)seachRequest{
    [ApplicationDelegate.webAPI getWebAPIWithParams:@{TYPE:@"1020"} andMethodNode:NODE_DIRECTORY completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        if (state ==1) {
            
            if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
                NSArray * arr = responseObject[@"PACKAGE_RSP"][@"PACKAGE"];
                _titlesArray = [@[]mutableCopy];

                for (NSDictionary * nameArr in arr) {
                    [_titlesArray addObject:nameArr[@"NAME"]];
                }
                
                [self seachHotWord];
            }
            
        }
    }];

}
-(void)seachHotWord
{
    NSMutableArray *colorArray = [@[[UIColor greenColor],[UIColor blueColor],[UIColor purpleColor],[UIColor redColor],[UIColor grayColor],[UIColor magentaColor],[UIColor brownColor],[UIColor yellowColor],[UIColor cyanColor]]mutableCopy];
    NSMutableArray *frameArray = [[NSMutableArray alloc] initWithObjects:@"{{54, 111}, {200, 70}}",@"{{26, 228}, {120, 70}}",@"{{132, 124}, {50, 70}}",@"{{64, 146}, {120, 80}}",@"{{180, 175}, {420, 70}}",@"{{54, 190}, {120, 40}}",@"{{132, 238}, {44, 70}}",@"{{170, 269}, {400, 70}}",@"{{47, 290}, {10, 70}}", nil];
    //如果文字给颜色多，颜色就自我复制
    while (_titlesArray.count>colorArray.count) {
        [colorArray addObjectsFromArray:colorArray];
    }
    NSMutableArray * labelArr = [@[]mutableCopy];
    
    
    for (int i = 0 ;i<_titlesArray.count;i++) {
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectZero];
        
        label.text = [_titlesArray objectAtIndex:i];
        int num = arc4random()%[colorArray count];
        label.textColor = colorArray[num];
        [colorArray removeObjectAtIndex:num];
        label.font = [UIFont boldSystemFontOfSize:k_FontSize];
        [self.view addSubview:label];
        
        label.center = self.view.center;
        [labelArr addObject:label];
        label.userInteractionEnabled = YES;
        //加手势
        UITapGestureRecognizer * tapVc = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didselectText:)];
        [label addGestureRecognizer:tapVc];
    }
  
    
        NSString * frameString;
    while (_titlesArray.count>=frameArray.count) {
        

            int w = arc4random()%100+44;
            int h = arc4random()%100+100;
            int x=arc4random()%(int)(320-w/2)+w/2;
            int y= arc4random()%(int)(568-h/2-44)+100;
            frameString = [NSString stringWithFormat:@"{{%d, %d}, {%d, %d}}",x,y,w,h];

            NSLog(@"%@",frameString);
        if (![frameArray containsObject:frameString]) {
             [frameArray addObject:frameString];
        }
        

        
    }
    
     for (int i = 0 ;i<labelArr.count;i++) {

         UIView *label = labelArr[i];
       
        if ([label isMemberOfClass:[UILabel class]]) {
             int rand =arc4random()%[frameArray count];
            [UIView animateWithDuration:2 animations:^{
                
                label.frame = CGRectFromString(frameArray[rand]);
                NSLog(@"%@",frameArray[rand]);
               
            } completion:nil];
             [label sizeToFit];
             [frameArray removeObjectAtIndex:rand];

        }
        
    }
}

- (void)initNavigation
{
    self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"1136bg"]];

    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"搜索";
    [self.weChatNavigationBar.rightButton setImage:nil forState:0];
    [self.weChatNavigationBar .leftButton addTarget:self action:@selector(exit)  forControlEvents:UIControlEventTouchUpInside];
    
    
}
- (IBAction)seachAction:(id)sender
{
    [self keyHidden];

    
    TRsearchViewController * VC=[self.storyboard instantiateViewControllerWithIdentifier:@"TRsearchViewController"];
    VC.searchString=self.seachWordTF.text;

    VC.searchInString=self.directorys[self.selectIndex][@"ID"];
    
    
    [self.navigationController pushViewController:VC animated:YES];
    
    
}
-(void)didselectText:(UITapGestureRecognizer*)tap{
    UILabel * label = (UILabel *)tap.view;
    
    [UIView animateWithDuration:.8f animations:^{
        label.center = CGPointMake(self.seachWordTF.center.x, self.seachWordTF.center.y);
        
    } completion:^(BOOL finished) {
        self.seachWordTF.text = label.text;
        [label removeFromSuperview];
    }];
    
    
}
-(void)updateKeyWordsUI:(NSArray *)keyWords
{
	KYRecentSearchView *recentSearchView = [[KYRecentSearchView alloc] initWithRecentSearches:keyWords];
    recentSearchView.frame = CGRectMake(0, 80, 320, 100);
}

-(void)keyHidden
{
    [self.seachInTF resignFirstResponder];
    [self.seachWordTF resignFirstResponder];

}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.seachInTF]) {
        return NO;
    }
    return YES;
}

-(void)exit
{
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}



- (IBAction)changeOpenStatus:(id)sender {
    _tb.hidden=NO;
    if (isOpened) {
        
        
        
        [UIView animateWithDuration:0.3 animations:^{
            UIImage *closeImage=[UIImage imageNamed:@"dropdown.png"];
            [_openButton setImage:closeImage forState:UIControlStateNormal];
            
            CGRect frame=_tb.frame;
            
            frame.size.height=1;
            [_tb setFrame:frame];
            
        } completion:^(BOOL finished){
            
            isOpened=NO;
        }];
    }else{
        
        
        [UIView animateWithDuration:0.3 animations:^{
            UIImage *openImage=[UIImage imageNamed:@"dropup.png"];
            [_openButton setImage:openImage forState:UIControlStateNormal];
            
            CGRect frame=_tb.frame;
            
            frame.size.height=300;
            [_tb setFrame:frame];
            [self.view addSubview:_tb];
        } completion:^(BOOL finished){
            
            isOpened=YES;
        }];
        
        
    }
}

- (IBAction)hiddenKey:(UIControl *)sender
{
    [self.seachWordTF resignFirstResponder];
    
}
@end
